// VBConversions Note: VB project level imports
using System.Data;
using DevExpress.XtraEditors.Controls;
using System.Diagnostics;
using System.Xml.Linq;
using DevExpress.XtraEditors.Repository;
using System.Collections.Generic;
using System.Data.SqlClient;
using Microsoft.VisualBasic;
using System.Configuration;
using System.Collections;
using DevExpress.XtraEditors;
using System.Data.Sql;
using Microsoft.SqlServer;
using System.Windows.Forms;
using System;
using DevExpress.XtraReports;
using Microsoft.SqlServer.Management.Smo;
using DevExpress;
using System.Linq;
using System.IO;
// End of VB project level imports


/// <summary>
/// This class Build View base on MetaQuery information
/// We will use this class to map SQL result to a View
/// The view is a DataTable created, base on Visible Column
/// </summary>
/// <remarks></remarks>
namespace SCIEF.SysBFW.CommonExt
{
	public class MetaDataView
	{
		
		private DataTable _view = null;
		
		/// <summary>
		/// Use to contains the Mapped values, from a Metaquery Result
		/// The MetaQuery return a List of Type Tranformation
		/// </summary>
		/// <remarks></remarks>
		private Dictionary<string, Dictionary<string, string>> lookups;
		
		/// <summary>
		/// The name of the MetaQuery
		/// </summary>
		/// <value></value>
		/// <returns></returns>
		/// <remarks></remarks>
		public string QueryName {get; set;}
		public string SQLWhere {get; set;}
		public MetaQuery MetaCommand {get; set;}
		
		/// <summary>
		/// The ResultSet base on the Visible Column
		/// </summary>
		/// <value></value>
		/// <returns></returns>
		/// <remarks>All ColumnName will be the Caption from the MetaQuery.MetaColumns</remarks>
		public DataTable View
		{
			get
			{
				return _view;
			}
		}
		
		/// <summary>
		/// Result of a MetaQuery Statement
		/// </summary>
		/// <value></value>
		/// <returns></returns>
		/// <remarks></remarks>
		public DataTable ResultQuery {get; set;}
		public MetaDataView()
		{
			lookups = new Dictionary<string, Dictionary<string, string>>();
		}
		
		public MetaDataView(string queryName) : this()
		{
			this.QueryName = queryName;
		}
		
		/// <summary>
		/// Go get the MetaCommand so we can modify the SQL Statement
		/// </summary>
		/// <remarks></remarks>
		public void GetMetaCommand()
		{
			MetaCommand = MetaQuery.GetMetaQueryByName(this.QueryName);
		}
		
		/// <summary>
		/// Construct a new DataTable base on visible metacolumns
		/// </summary>
		/// <remarks></remarks>
		public void BuildMetaView()
		{
			DataTable dt = default(DataTable);
			//Dim colMq As DataColumn
			if (MetaCommand == null)
			{
				GetMetaCommand();
			}
			if (MetaCommand != null)
			{
				if (this.ResultQuery == null)
				{
					if (!string.IsNullOrEmpty(this.SQLWhere))
					{
						MetaCommand.SQLWhereContext = this.SQLWhere;
					}
					MetaCommand.FillResultQuery();
					this.ResultQuery = MetaCommand.ResultQuery.Copy();
				}
				//
				dt = this.ResultQuery.Copy();
			}
			else
			{
				throw (new Exception("MetaQuery does not exist:" + this.QueryName));
			}
			_view = dt;
		}
		
		
		/// <summary>
		/// Rename ColumnName for Caption and Delete Invisible Columns
		/// </summary>
		/// <remarks></remarks>
		private void RestructureView()
		{
			
			DataColumn colForMetaView = default(DataColumn);
			bool colVisible;
			foreach (DataRow row in MetaCommand.MetaColumns.Rows)
			{
				//
				colVisible = (System.Convert.ToInt32(row["pVisible"]) == 0) ? false : true;
				colForMetaView = _view.Columns[row["ColumnName"].ToString()];
				//
				if (colVisible == true)
				{
					//
					if (!Microsoft.VisualBasic.Information.IsDBNull(row["pCaption"]))
					{
						//colForMetaView.Caption = row("pCaption").ToString
						colForMetaView.ColumnName = row["pCaption"].ToString();
					}
					//
					//colForMetaView.ReadOnly = Not CBool(row("pLocked"))
					//
					if (!Microsoft.VisualBasic.Information.IsDBNull(row["pDataWidth"]) && System.Convert.ToInt32(row["pDataWidth"]) > 0)
					{
						colForMetaView.MaxLength = System.Convert.ToInt32(row["pDataWidth"]);
					}
				}
				else
				{
					_view.Columns.Remove(colForMetaView);
				}
			}
		}
		
		/// <summary>
		/// Insert the information in the view
		/// </summary>
		/// <remarks></remarks>
		public void FillView()
		{
			if (_view == null)
			{
				BuildMetaView();
			}
			PrepareDataMapping();
			if (lookups.Count > 0)
			{
				TransformDataMapping();
			}
			TransformDataRow();
			RestructureView();
		}
		
		/// <summary>
		/// Replace the columns values from their corresponding Mapped Values contains in the Dictionary associate to the columns
		/// </summary>
		/// <remarks></remarks>
		private void TransformDataMapping()
		{
			Dictionary<string, string> lookup = default(Dictionary<string, string>);
			KeyValuePair<string, Dictionary<string, string>> mapValues = new KeyValuePair<string, Dictionary<string, string>>();
			string sourceValue = default(string);
			//On each row...
			foreach (DataRow row in _view.Rows)
			{
				//On each Colomns with LOVs
				foreach (KeyValuePair<string, Dictionary<string, string>> tempLoopVar_mapValues in lookups)
				{
					mapValues = tempLoopVar_mapValues;
					lookup = mapValues.Value;
					sourceValue = row[mapValues.Key].ToString();
					//Change the value for it's mapping value
					if (lookup.ContainsKey(sourceValue))
					{
						row.Table.Columns[mapValues.Key].ReadOnly = false;
						row[mapValues.Key] = lookup[sourceValue];
					}
				}
			}
		}
		
		private void TransformDataRow()
		{
			
		}
		
		/// <summary>
		/// Go Get LOVs Code and Values and fill Dictionnary Collections
		/// </summary>
		/// <remarks></remarks>
		private void PrepareDataMapping()
		{
			this.MetaCommand.GetLOV_LKP();
			if (this.MetaCommand.HasLov)
			{
				BuildLookupsDictionaries(this.MetaCommand.ListOfLov);
			}
		}
		
		/// <summary>
		/// Base on the LOVs we built Dictionnary collection so it's faster to transform later
		/// </summary>
		/// <param name="lovs">Dirtionary of ColumnName, Guid of MetaQuery</param>
		/// <remarks></remarks>
		private void BuildLookupsDictionaries(Dictionary<string, Guid> lovs)
		{
			Dictionary<string, string> lookup = default(Dictionary<string, string>);
			//Scan the LOVs collection of the Metaquery
			foreach (KeyValuePair<string, Guid> pair in lovs)
			{
				using (MetaQuery mq = MetaQuery.GetMetaQueryById(pair.Value))
				{
					if (mq != null)
					{
						mq.FillResultQuery();
						//Kept the results columns of the LOvs
						if (mq.ResultQuery.Rows.Count > 0)
						{
							lookup = new Dictionary<string, string>();
							foreach (DataRow row in mq.ResultQuery.Rows)
							{
								lookup.Add(row["ValueCD"].ToString(), row["Value_EXT"].ToString());
							}
							lookups.Add(pair.Key, lookup);
						}
					}
				}
				
			}
		}
		
		/// <summary>
		/// Go get the result from MetaQuery
		/// </summary>
		/// <remarks></remarks>
		public void FillResultQuery()
		{
			using (MetaQuery mq = MetaQuery.GetMetaQueryByName(this.QueryName))
			{
				if (mq != null && this.ResultQuery != null)
				{
					if (!string.IsNullOrEmpty(this.SQLWhere))
					{
						MetaCommand.SQLWhereContext = this.SQLWhere;
					}
					mq.FillResultQuery();
					this.ResultQuery = mq.ResultQuery.Copy();
				}
				else
				{
					throw (new Exception("MetaQuery does not exist:" + this.QueryName));
				}
			}
			
		}
		
		
		
	}
	
}
